package de.pharmacontrol.psa.beans.managed;

import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import de.pharmacontrol.pilot.entities.LogEntry;
import de.pharmacontrol.psa.beans.interfaces.LogEntryService;

/**
 * Session Bean implementation class LogEntryBean
 */
@ManagedBean(name = "lazyLogBean")
@SessionScoped
public class LazyLogBean {

	private LazyDataModel<LogEntry> lazyModel;

	private String searchPattern;

	@EJB
	LogEntryService logService;

	private LogEntry selectedLogEntry;

	public LazyDataModel<LogEntry> getLazyModel() {
		lazyModel.setRowCount(getLogEntryCount());
		return lazyModel;
	}

	public LogEntry getSelectedLogEntry() {
		return selectedLogEntry;
	}

	public void setSelectedLogEntry(LogEntry selectedLogEntry) {
		System.err.println(selectedLogEntry.getMessage());
		this.selectedLogEntry = selectedLogEntry;
	}

	public LazyLogBean() {

	}

	@PostConstruct
	public void init() {
		lazyModel = new LazyDataModel<LogEntry>() {

			private static final long serialVersionUID = 8910202724086345181L;

			@Override
			public List<LogEntry> load(int first, int pageSize, String sortField, SortOrder order, Map<String, String> filters) {

				Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.INFO, "Loading the LogEntries between {0} and {1} / filter: {2} and order: {3}", new Object[] { first, (first + pageSize), searchPattern, order });

				List<LogEntry> list = logService.findPagedLogEntries(first, pageSize, searchPattern, SortOrder.ASCENDING.equals(order));
				
				Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.INFO, "Loading the LogEntries data size: {0}", new Object[] { list.size() });

				return list;
			}

		};
		lazyModel.setRowCount(getLogEntryCount());
	}

	private Integer maxCount = null;

	public int getLogEntryCount() {
		if (maxCount == null) {
			if (searchPattern == null || searchPattern.isEmpty()) {
				maxCount = logService.getLogEntryCount();
			} else {
				maxCount = logService.getLogEntryCount(searchPattern);
			}
		}
		return maxCount;
	}

	public void setSearchPattern(String searchPattern) {
		this.searchPattern = searchPattern;
	}

	public String getSearchPattern() {
		return searchPattern;
	}

	public String searchPattern() {
		maxCount = null;
		lazyModel.setRowCount(getLogEntryCount());
		return "home";
	}
}
